#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <pthread.h>

using std::cout;
using std::endl;

int tickets = 100;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void* get_ticket(void* args)
{
    std::string username = static_cast<const char *>(args);
    while(true)
    {
        pthread_mutex_lock(&lock);
        if(tickets>0)
        {
            usleep(11111);
            cout<<username<<"正在抢票 : "<<tickets<<endl;
            tickets--;
            pthread_mutex_unlock(&lock);
        }
        else
        {
            pthread_mutex_unlock(&lock);
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_t t1, t2, t3, t4;
    pthread_create(&t1, nullptr,  get_ticket, (void *)"thread 1");
    pthread_create(&t2, nullptr,  get_ticket, (void *)"thread 2");
    pthread_create(&t3, nullptr,  get_ticket, (void *)"thread 3");
    pthread_create(&t4, nullptr, get_ticket, (void *)"thread 4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);
    return 0;
}